/*
 * Copyright (C) 2010-2011 sunjumper@163.com
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *  http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package mf.mfrpc.parser;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import com.caucho.hessian.io.SerializerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import mf.mfrpc.serialize.Parser;
import mf.mfrpc.serialize.SerializationException;

/**
 * Hessian序列化。
 */
public class HessianParser implements Parser {

    private final static SerializerFactory serializerFactory = new SerializerFactory();

    static {
        serializerFactory.setAllowNonSerializable(true);
        //serializerFactory.setSendCollectionType(true);
    }

    @Override
    public void writeObject(OutputStream output, Object object) {
        Hessian2Output oos = new Hessian2Output(output);
        oos.setSerializerFactory(serializerFactory);
        try {
            oos.writeObject(object);
            oos.flush();
        } catch (IOException e) {
            throw new SerializationException(e);
        }

    }

    @Override
    public <T> T readObject(InputStream input) {
        Hessian2Input ois = new Hessian2Input(input);
        ois.setSerializerFactory(serializerFactory);
        try {
            return (T) ois.readObject();
        } catch (IOException e) {
            throw new SerializationException(e);
        }
    }

    @Override
    public <T> T readObject(InputStream input, Class<T> type) {
        Hessian2Input ois = new Hessian2Input(input);
        ois.setSerializerFactory(serializerFactory);
        try {
            return (T) ois.readObject(type);
        } catch (IOException e) {
            throw new SerializationException(e);
        }
    }
}
